package com.csair.platform.cit.service.core.aop;

import com.csair.invoice.common.base.vo.JsonResult;
import com.csair.platform.cit.facade.exception.CitBizException;
import com.csair.platform.cit.service.feignclient.basedata.CcuAuthorizeClient;
import lombok.extern.log4j.Log4j2;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * 使用@Aspect注解声明一个切面
 *
 * @author dahai
 */
@Aspect
@Component
@Log4j2
public class TaxCategoryAuthAspect {

    /**
     * 该拦截器是否开启
     */
    @Value("${taxCategory.auth.openFlag: true}")
    private boolean taxCategoryAuthOpenFlag;

    @Autowired
    private CcuAuthorizeClient ccuAuthorizeClient;


    @Pointcut("@annotation(com.csair.platform.cit.service.core.CheckDataPermission)")
    public void executeService() {

    }

    @Before("executeService()")
    public void doBeforeAdvice(JoinPoint joinPoint) {
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = servletRequestAttributes.getRequest();
        String requestURI = request.getRequestURI();
        log.info("TaxCategoryAspect  doBeforeAdvice  路径:{}", request.getRequestURI());
        //开关是否关闭
        if (!taxCategoryAuthOpenFlag) {
            return;
        }
        //是否认证通过
        this.checkAuth(requestURI);
    }

    public void checkAuth(String requestURI) {
        //企业所得税的
        final String categoryId = "10002";

        //是否校验通过， true通过，false 为未通过
        boolean auth = true;
        try {
            JsonResult<Boolean>   booleanJsonResult = ccuAuthorizeClient.checkAuth(categoryId);
            auth= booleanJsonResult.getData().get(0).booleanValue();
        } catch (Exception exception) {
            handleFailResult(CitBizException.TAX_NO_AUTH_ERROR, "调用接口错误");
        }
        if (!auth) {
            log.info("TaxCategoryAuthAspect  doBeforeAdvice  拦截路径:{},税种：{} 不存在授权列表中", requestURI, categoryId);
            handleFailResult(CitBizException.TAX_NO_AUTH_ERROR, "无权限操作，请联系管理员");
        }

    }

    /**
     * 将错误信息添加到 response 中
     *
     * @param code
     * @param errorMessage
     */
    public void handleFailResult(Integer code, String errorMessage) {
        throw new CitBizException(code, errorMessage);
    }
}
